package userinterface;

import Rijndael.Decoder;
import Rijndael.Encoder;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import org.apache.log4j.Logger;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.text.AbstractDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by IntelliJ IDEA.
 * User: dima
 * Date: 17.09.2010
 * Time: 20:43:52
 * пользовательский интерфейс
 */
public class MainForm {
    public static final Logger log = Logger.getLogger(MainForm.class);

    private JTextField textFieldOpen;
    private JPanel panel1;
    private JTextField textFieldKey;
    private JTextField textFieldCipher;
    private JButton startButton;
    private static final int FORM_WIDTH = 400;
    private static final int FORM_HEIGHT = 150;
    private static final int TEXT_LENGTH = 32;

    public MainForm() {
//      забрасываем сгенерированную панельку на форму
        JFrame mainFrame = new JFrame("AESCoder");
        mainFrame.getContentPane().add(panel1);
        mainFrame.setSize(FORM_WIDTH, FORM_HEIGHT);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);

//      прикручиваем случатель кнопки
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                log.debug("startButton action performed");
//___________________TEST__ZONE_________________________
//                short[][] in = new short[4][4];
//                String inStr = "1111111111111111ffffffffffffffff";
//                int strPos = 0;
//                for (int i = 0; i < 4; i++) {
//                    for (int j = 0; j < 4; j++) {
////                преобразуем два подряд идущих символа в байт
////                для открытого текста
//                        String twoChars = inStr.substring(strPos, strPos + 2);
//                        in[i][j] = (short) Integer.parseInt(twoChars, 16);
//                        strPos += 2;
//                    }
//                    log.debug("" + Integer.toHexString(in[i][0]) + " " + Integer.toHexString(in[i][1]) + " " + Integer.toHexString(in[i][2]) + " " + Integer.toHexString(in[i][3]));
//                }
//___________________TEST__ZONE_________________________
                if ((textFieldOpen.getText().length() == TEXT_LENGTH) &&
                        (textFieldKey.getText().length() == TEXT_LENGTH)) {
                    log.debug("запуск кодирования");
                    String encodedText = Encoder.encode(textFieldOpen.getText(), textFieldKey.getText());
                    log.debug("encoded text - " + encodedText);
                    textFieldCipher.setText(encodedText);
                } else if ((textFieldCipher.getText().length() == TEXT_LENGTH) &&
                        (textFieldKey.getText().length() == TEXT_LENGTH)) {
                    log.debug("запуск декодирования");
                    String decodedText = Decoder.decode(textFieldCipher.getText(), textFieldKey.getText());
                    log.debug("decoded text - " + decodedText);
                    textFieldOpen.setText(decodedText);
                }
            }
        });

//      ограничитель набора текста (невозможно набрать больше чем TEXT_LENGTH символов)
//        AbstractDocument doc = (AbstractDocument) textFieldOpen.getDocument();
//        doc.setDocumentFilter(new LengthFilter(doc.getLength(), TEXT_LENGTH));
        ((AbstractDocument) textFieldOpen.getDocument()).setDocumentFilter(new LengthFilter(textFieldOpen.getDocument().getLength(), TEXT_LENGTH));
        ((AbstractDocument) textFieldKey.getDocument()).setDocumentFilter(new LengthFilter(textFieldOpen.getDocument().getLength(), TEXT_LENGTH));
        ((AbstractDocument) textFieldCipher.getDocument()).setDocumentFilter(new LengthFilter(textFieldOpen.getDocument().getLength(), TEXT_LENGTH));
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(4, 2, new Insets(0, 0, 0, 0), 0, 0, false, true));
        panel1.setAutoscrolls(false);
        panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font(panel1.getFont().getName(), panel1.getFont().getStyle(), panel1.getFont().getSize())));
        textFieldOpen = new JTextField();
        textFieldOpen.setColumns(10);
        panel1.add(textFieldOpen, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        final JLabel label1 = new JLabel();
        label1.setText("Открытый текст");
        panel1.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        textFieldKey = new JTextField();
        panel1.add(textFieldKey, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        final JLabel label2 = new JLabel();
        label2.setText("Ключ");
        panel1.add(label2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        textFieldCipher = new JTextField();
        textFieldCipher.setText("");
        panel1.add(textFieldCipher, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        final JLabel label3 = new JLabel();
        label3.setText("Шифротекст");
        panel1.add(label3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        startButton = new JButton();
        startButton.setText("Старт");
        startButton.setVisible(true);
        panel1.add(startButton, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return panel1;
    }
}
